﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using DllConfig;
using StockService.ProxyService;
using StockWcf;
using StockWcf.Manager;

namespace StockService
{
    public partial class WindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;
       

        public WindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                if (serviceHost == null)
                {
                    serviceHost = new ServiceHost(typeof (StockWcfService));
                    serviceHost.Open();
                    Log.Write("服务成功启动.");
                    StockServiceEnable();
                  
                    //服务启动成果，开始进行交易
                    TradeManager.Execute();

                    MarketManager.MarketServiceStart();
                }
            }
            catch (Exception exp)
            {
                Log.Write(exp.Message);
            }
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
            Log.Write("服务已经关闭.");
            StockServiceDisable();
            MarketManager.MarketServiceStop();
        }

        #region 代理服务相关
        public static WcfSPClient ProxyClient()
        {
            var binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = 2147483647;
            var endPoint = new EndpointAddress(StockConfig.StockProxyUri); // WCF 地址只与这里有关！
            var client = new WcfSPClient(binding, endPoint);

            return client;
        }

        public static void StockServiceEnable()
        {
            try
            {
                var client = ProxyClient();
                client.SetState(true);
            }
            catch (Exception exp)
            {
                Log.Write(exp.Message);
            }
        }
        public static void StockServiceDisable()
        {
            try
            {
                var client = ProxyClient();
                client.SetState(false);
            }
            catch (Exception exp)
            {
                Log.Write(exp.Message);
            }
        }

        #endregion
    }
}
